package com.xintonghua.base.ui;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.gyf.barlibrary.ImmersionBar;
import com.xintonghua.base.BuildConfig;
import com.xintonghua.base.R;
import com.xintonghua.base.utils.AllActivitiesHolder;
import com.xintonghua.base.utils.MyUtils;


/**
 * 作者 ： win7 on 2016/3/22 10:50
 * 项目名：Ucar activity的基类
 * 包名：  com.jiajiabao.ucarenginner.base
 */
public class BaseActivity extends AppCompatActivity {

    private boolean mOverrideExitAniamtion = false;
    private boolean mIsFinishing;

    protected boolean isVisible = true;
    protected ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AllActivitiesHolder.addAct(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        registerEventBus();
    }


    /**
     * @title 最简单的actionbar
     * @desc 中间标题
     * @desc 返回上一层
     */
    public void onSimpleActionBar() {
        onSimpleActionBar(R.layout.activity_base_simple);
    }


    public void onSimpleActionBar(int layResId) {
        android.support.v7.app.ActionBar _actionBar = getSupportActionBar();
        _actionBar.setDisplayShowCustomEnabled(true);
        _actionBar.setCustomView(layResId);
        _actionBar.setDisplayShowHomeEnabled(false);
        _actionBar.setDisplayHomeAsUpEnabled(false);
        _actionBar.setDisplayUseLogoEnabled(false);
        _actionBar.setDisplayShowTitleEnabled(false);
        _actionBar.getCustomView().findViewById(android.R.id.home).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyUtils.hideSoftInput(BaseActivity.this);
                finish();
            }
        });
        _actionBar.setElevation(0);
        //for theme AppCompat
        int actionBarHeight = getResources().getDimensionPixelOffset(R.dimen.abc_action_bar_stacked_max_height);
        Toolbar parent = (Toolbar) _actionBar.getCustomView().getParent();
        parent.setContentInsetsAbsolute(0, 0);
        parent.setMinimumHeight(actionBarHeight);
        ViewGroup.LayoutParams v = parent.getLayoutParams();
        v.height = actionBarHeight;
        parent.setLayoutParams(v);
    }


    public void setSimpleActionBar(String title, String actionText, View.OnClickListener actionlistener) {
        android.support.v7.app.ActionBar _actionBar = getSupportActionBar();
        TextView _title = (TextView) _actionBar.getCustomView().findViewById(android.R.id.title);

        _title.setText(TextUtils.isEmpty(title) ? "" : title);
        if (TextUtils.isEmpty(actionText)) {
            return;
        }
        TextView _action = (TextView) _actionBar.getCustomView().findViewById(R.id.action);
        _action.setVisibility(View.VISIBLE);
        _action.setText(actionText);
        _action.setOnClickListener(actionlistener);
    }

    public void setSimpleActionBar(String title, int img, View.OnClickListener actionlistener) {
        android.support.v7.app.ActionBar _actionBar = getSupportActionBar();
        TextView _title = (TextView) _actionBar.getCustomView().findViewById(android.R.id.title);

        _title.setText(TextUtils.isEmpty(title) ? "" : title);
        if (img == 0) {
            return;
        }
        ImageView _action = (ImageView) _actionBar.getCustomView().findViewById(R.id.action_image);
        _action.setVisibility(View.VISIBLE);
        _action.setImageResource(img);
        _action.setOnClickListener(actionlistener);
    }

    public void setSimpleActionBar(int title, int actionText, View.OnClickListener actionlistener) {
        setSimpleActionBar(getString(title), actionText == 0 ? "" : getString(actionText), actionlistener);
    }

    public void setSimpleActionBar(int title) {
        setSimpleActionBar(getString(title));
    }

    public void setSimpleActionBar(String title) {
        setSimpleActionBar(title, "", null);
    }

    /**
     * Toast提示
     *
     * @param resId
     */
    public void mToast(int resId) {
        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
    }

    public void mToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 从EditText 获取字符
     *
     * @param editText
     * @return
     */
    public String getStr(EditText editText) {
        return editText.getText().toString().trim();
    }

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public boolean isNull(String str) {
        if (null == str || "".equals(str) || "null".equalsIgnoreCase(str)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 通过类名启动Activity，并且含有Bundle数据
     *
     * @param pBundle
     */
    protected void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
    }

    protected void openActivity(Class<?> pClass, Parcelable data) {
        Intent intent = new Intent(this, pClass);
        Bundle bundle = new Bundle();
        bundle.putParcelable(BuildConfig.FLAVOR, data);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    /**
     * 通过类名启动Activity
     *
     * @param pClass
     */
    protected void openActivity(Class<?> pClass) {
        openActivity(pClass, new Bundle());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }


    @Override
    public void finish() {
        if (mOverrideExitAniamtion && !mIsFinishing) {
            mIsFinishing = true;
            return;
        }
        mIsFinishing = false;
        super.finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        isVisible = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isVisible = false;
        dismissDialog();
    }


    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        config.fontScale = 1;
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }


    /**
     * @title 显示加载中progress dialog
     */

    public void showDialog() {
        DialogFragment newFragment = (ProgressingFragment) getSupportFragmentManager().findFragmentByTag(ProgressingFragment.TAG);
        if (newFragment == null) {
            newFragment = ProgressingFragment.newInstance();
        }
        if (!newFragment.isAdded()) {//如果已经添加 就不用再次添加
            newFragment.show(getSupportFragmentManager(), ProgressingFragment.TAG);
        }
    }

    /**
     * @title 取消显示dialog
     */
    public void dismissDialog() {
        //判断 是否是最后一个耗时线程执行完毕
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(ProgressingFragment.TAG);
        if (fragment != null && !fragment.isHidden()) {
            DialogFragment dialog = (DialogFragment) fragment;
            dialog.dismissAllowingStateLoss();
        }
    }

    public static class ProgressingFragment extends android.support.v4.app.DialogFragment {
        private static final String TAG = ProgressingFragment.class.getSimpleName();

        public static ProgressingFragment newInstance() {
            return new ProgressingFragment();
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Dialog progressDialog = new Dialog(getActivity(), R.style.loadingDialog);
            //progressDialog.setContentView(R.layout.loading_circle);
            return progressDialog;
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AllActivitiesHolder.removeAct(this);
        unregisterEventBus();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
    }


    /**
     * @param phoneNumber
     * @title 拨打电话
     */
    public void callDial(String phoneNumber) {
        callDialTel("tel:" + phoneNumber);
    }

    public void callDialTel(String phoneProtocol) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse(phoneProtocol));
        startActivity(intent);
    }

    /**
     * 初始化UI
     */
    public void initUI() {
    }


    public void registerEventBus() {
        // EventBus.getDefault().register(this);

    }

    public void unregisterEventBus() {
        //EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
    }


}
